package com.zb.system.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.zb.entity.AccounLoginInfo;
import com.zb.exception.SMSException;
import com.zb.redis.RedisLoginTokenUtil;
import com.zb.result.Result;
import com.zb.system.service.LoginService;
import com.zb.utils.TokenUtil;
import com.zb.vo.LoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @Author WEN
 * @Date 2023/7/18 0018
 **/
@Api(tags = "登录类接口")
@RestController
@RequestMapping("/system/login")
public class LoginController {
    @Resource
    private LoginService loginService;

    @ApiOperation("登录")
    @PostMapping("/")
    public Result login(@RequestBody @Valid LoginVo loginVo) throws SMSException {
        return Result.success("登录成功").data("row", loginService.login(loginVo));
    }

    @ApiOperation(value = "刷新token")
    @GetMapping("/refreshToken")
    public Result refreshToken(@ApiParam(value = "刷新token", required = true) String refreshToken) throws LoginException {
        return Result.success("登录成功").data("row", loginService.refreshToken(refreshToken));
    }

    @ApiOperation(value = "退出登录")
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {
        String accessToken = TokenUtil.getToken(request);
        RedisLoginTokenUtil.removeAllTokenByAccessToken(accessToken);
        StpUtil.logoutByTokenValue(accessToken);
        return Result.success("退出登录成功！");
    }

    @ApiOperation("获取与账号关联的所有企业")
    @GetMapping("/getCustomer")
    public Result getCustomer(HttpServletRequest request) {
        AccounLoginInfo accountLoginInfo = TokenUtil.getAccountLoginInfo(request);
        return Result.success("获取企业成功！").data("row", loginService.getCustomerByAccountId(accountLoginInfo));
    }

    @ApiOperation("选择企业")
    @GetMapping("/getCustomerCode")
    public Result getCustomerCode(HttpServletRequest request, @RequestParam @ApiParam(value = "企业编码", required = true) String code) {
        String accessToken = TokenUtil.getToken(request);
        AccounLoginInfo accountLoginInfo = TokenUtil.getAccountLoginInfo(accessToken);
        loginService.getCustomerCode(accountLoginInfo, code);
        RedisLoginTokenUtil.setAccountLoginInfoByAccessToken(accessToken, accountLoginInfo);
        return Result.success();
    }


}
